#pragma once

#include<iostream>
#include<vector>
#include<pthread.h>
#include<semaphore.h>
#include<cctype>
using namespace std;


static  const int n =5;

template<class T>
class Ringqueue
{
    //封装
    void P(sem_t &st)
    {
        sem_wait(&st);
    }
    void V(sem_t &st)
    {
        sem_post(&st);
    }

    void Lock(pthread_mutex_t & mt)
    {
        pthread_mutex_lock(&mt);
    }
    void Unlock(pthread_mutex_t &mt)
    {
        pthread_mutex_unlock(&mt);
    }




public:
    Ringqueue(int num=n):_ring(num),_cap(num)
    {
        sem_init(&_data_sem,0,0);    //从0位置开始消费
        sem_init(&_space_sem,0,num); //生产者所要生产的区间最大值num

        _c_step=_p_step=0;//一开始生产者消费者位置

        pthread_mutex_init(&_c_mutex,nullptr);
        pthread_mutex_init(&_p_mutex,nullptr);
    }

    void push(const T &in)
    {
        P(_space_sem);
        Lock(_c_mutex);
        _ring[_p_step++]=in;
        _p_step %= _cap;
        Unlock(_c_mutex);
        V(_data_sem);


    }
    void pop(T* out)
    {
        P(_data_sem);
        Lock(_c_mutex);
        *out=_ring[_c_step++];
        _c_step%=_cap;

        Unlock(_c_mutex);
        V(_space_sem);




    }


    ~Ringqueue()
    {
        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);

        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }




private:
    vector<T> _ring;
    int _cap;           //_ring的大小
    sem_t _data_sem;  //消费者
    sem_t _space_sem; //生产者
    int _c_step;      //消费者位置
    int _p_step;      //生产者位置

    pthread_mutex_t _c_mutex;   
    pthread_mutex_t _p_mutex;
};